<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="账号说明" prop="accountDescription">
        <el-input
          v-model="queryParams.accountDescription"
          placeholder="账号说明.."
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >添加DNS账号信息
        </el-button>
      </el-col>
    </el-row>

    <!-- 表格展示DNS服务商数据 -->
    <el-table v-loading="loading" :data="providersList" @selection-change="handleSelectionChange">
      <el-table-column label="账号说明" align="center" prop="accountDescription"/>
      <el-table-column label="服务商" align="center" prop="providerType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.edge_dns_providers" :value="scope.row.providerType"/>
        </template>
      </el-table-column>
      <el-table-column label="域名" align="center" prop="domainNum"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleInfo(scope.row)"
          >详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 弹窗：添加DNS服务商 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="账号说明" prop="accountDescription">
          <el-input v-model="form.accountDescription"/>
          <span class="el-form-item__helper">用来方便区分不同的账号。</span>
        </el-form-item>

        <el-form-item label="服务商厂家" prop="providerType">
          <el-select v-model="form.providerType">
            <el-option
              v-for="dict in dict.type.edge_dns_providers"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
          <span class="el-form-item__helper">CloudFlare提供的DNS服务.系统会保留原有域名下的域名解析,清放心使用</span>
        </el-form-item>

        <el-form-item label="账号邮箱" prop="apiUrl">
          <el-input v-model="form.apiUrl"/>
          <span class="el-form-item__helper">登录账号使用的邮箱。</span>
        </el-form-item>

        <el-form-item label="API密钥" prop="apiKey">
          <el-input v-model="form.apiKey"/>
          <span class="el-form-item__helper">在个人资料中的"API令牌"--"API密钥"--"Global API Key"中获取。为了安全起见，此项数据保存后将不允许在界面查看完整明文，为避免忘记，请自行记录原始数据。</span>
        </el-form-item>

        <el-form-item label="最小TTL（秒）" prop="minTTL">
          <el-input-number
            v-model="form.minTTL"
            :min="0"
            :max="3600"
            placeholder="请输入最小TTL（秒）"
            style="width: 100%"
          />
          <span
            class="el-form-item__helper">生成的DNS时可以使用的最小TTL，请根据你选择的服务商和你在服务商中的账号等级进行填写；不填写或者0表示默认。</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listProviders, getProviders, delProviders, addProviders, updateProviders} from "@/api/dns/providers";

export default {
  dicts: ['edge_dns_providers'],
  name: "Providers",
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      providersList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        accountDescription: null,
      },
      form: {
        accountDescription: '',
        apiUrl: '',
        apiKey: '',
        minTTL: null,
      },
      rules: {
        accountDescription: [
          {required: true, message: "账号说明不能为空", trigger: "blur"}
        ],
        providerName: [
          {required: true, message: "服务商名称不能为空", trigger: "blur"}
        ],
        providerType: [
          {required: true, message: "请选择服务商厂家", trigger: "change"}
        ],
        apiUrl: [
          {required: true, message: "API ID不能为空", trigger: "blur"}
        ],
        apiKey: [
          {required: true, message: "API密钥不能为空", trigger: "blur"}
        ]
      },
      domainNum: null
    };
    open:false
  },
  created() {
    this.getList();
  },
  methods: {
    // 账号详情
    handleInfo(row){
      console.log(row,'row')
      this.loading = true;
      this.$router.push({ name: 'ProvidersInfo', params: { providersInfo: row } }).catch(() => {});
    },
    getList() {
      this.loading = true;
      listProviders(this.queryParams).then(response => {
        this.providersList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        accountDescription: '',
        providerType: '',
        apiUrl: '',
        apiKey: '',
        minTTL: null,
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleAdd() {
      this.reset();
      this.title = "创建DNS服务商账号";
      this.open = true;
    },
    // 删除服务商账号
    handleDelete(row) {
      this.$confirm('您确定要删除此服务商账号吗？', '服务商账号', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error',
      })
        .then(() => {
          this.loading = true;  // 开始加载
          delProviders(row.id)
            .then(response => {
              this.loading = false;  // 加载完成
              // 删除成功，显示提示消息
              this.$message({
                message: '服务商账号删除成功',
                type: 'success',
              });
              this.getList();
            })
            .catch(error => {
              this.loading = false;  // 加载完成
              // 错误提示
              this.$message({
                message: '服务商账号删除失败，请重试',
                type: 'error',
              });
            });
        })
        .catch(() => {
          // 用户点击取消，什么也不做
          this.$message({
            message: '操作已取消',
            type: 'info',
          });
        });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$modal.loading("正在添加服务商");
          addProviders(this.form).then(response => {
            this.$modal.success("添加服务商成功");
            this.reset();
          }).finally(() => {
            this.open = false;
            this.getList();
            this.$modal.closeLoading();
          });
        }
      });
    }
  }
};
</script>

<style scoped>
.el-form-item__helper {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
  display: block;
}
</style>

